from flask import Flask, request, jsonify
from flask_cors import CORS
from flask_socketio import SocketIO, emit
import sqlite3
import json
import subprocess


#按照视频搜索所有对应数据
def get_video_data(video_name):
    try:
        # 连接到SQLite数据库
        conn = sqlite3.connect('video_database.db')
        c = conn.cursor()

        # 查询视频数据
        c.execute("SELECT * FROM videos WHERE name=?", (video_name,))
        video_data = c.fetchone()

        # 关闭连接
        conn.close()

        # 如果找到对应视频，则返回数据
        if video_data:
            return {
                "id": video_data[0],
                "name": video_data[1],
                "tags": video_data[2],
                "storage_path": video_data[3],
                "nodejson": video_data[4],
                "edgejson": video_data[5],
                "treejson": video_data[6],
                "content": video_data[7],
                "summary": video_data[8]
            }
        else:
            print("Video not found!")
            return None
    except Exception as e:
        print("Error getting video data:", e)
        return None
    
#联查：输入node返回查到的视频id(list)
def get_video_ids_by_node(node_content):
    try:
        # 连接到 SQLite 数据库
        conn = sqlite3.connect('video_database.db')
        c = conn.cursor()

        # 查询节点对应的视频 ID
        c.execute("SELECT video_id FROM link WHERE node=?", (node_content,))
        video_ids = c.fetchone()
        #输出找到的id列表
        # print(video_ids)
        # 关闭连接
        conn.close()

        # 如果找到对应视频 ID，则返回视频 ID
        if video_ids:
            return json.loads(video_ids[0])
        else:
            print("No videos found for the node:", node_content)
            return None

    except Exception as e:
        print("Error getting video IDs by node:", e)
        return None

#输入视频id（list）返回全部内容
def get_videos_data_by_ids(video_ids):
    try:
        # 连接到 SQLite 数据库
        conn = sqlite3.connect('video_database.db')
        c = conn.cursor()

        # 查询视频数据
        videos_data = []
        for video_id in video_ids:
            c.execute("SELECT * FROM videos WHERE id=?", (video_id,))
            video_data = c.fetchone()
            if video_data:
                videos_data.append({
                    "id": video_data[0],
                    "name": video_data[1],
                    "tags": video_data[2],
                    "storage_path": video_data[3],
                    "nodejson": video_data[4],
                    "edgejson": video_data[5],
                    "treejson": video_data[6],
                    "content": video_data[7]
                })

        # 关闭连接
        conn.close()

        return videos_data
    except Exception as e:
        print("Error getting videos data by IDs:", e)
        return None

app=Flask(__name__)
CORS(app)

socketio = SocketIO(app, cors_allowed_origins="*")

# 与前端实时通信，确认处理进度
def process_data(data):
   
    print("当前提取进度: %d%%" % data)
    socketio.emit('progress', {'progress': data}, namespace='/data')

    # 数据处理完成，发送处理完成的 JSON 数据给前端
    # data = {"result": "processed_data"}
    # socketio.emit('data_ready', data, namespace='/data')

def process_data2(data):
   
    print(data)
    socketio.emit('data_ready', {"result": data}, namespace='/data')

@socketio.on('connect', namespace='/data')
# def handle_connect():
#     # 当客户端连接时开始数据处理
#     socketio.start_background_task(process_data)

# 与transformer进程通信 
@socketio.on('connect', namespace='/transformer_')
def handle_connect():
    print('transformer_Client connected')

@socketio.on('transformer_message', namespace='/transformer_')
def handle_client_message(message_data):
    message = message_data['message']
    process_data(message)

# 与cpu_api进程通信 
@socketio.on('connect', namespace='/cpu_api')
def handle_connect():
    print('cpu_api_Client connected')

@socketio.on('cpu_api_message', namespace='/cpu_api')
def handle_client_message(message_data):
    message = message_data['message']
    process_data(message)
    
# 与generate_data进程通信 
@socketio.on('connect', namespace='/generate_data')
def handle_connect():
    print('generate_data_Client connected')

@socketio.on('generate_data_message', namespace='/generate_data')
def handle_client_message(message_data):
    message = message_data['message']
    process_data(message)

@socketio.on('generate_Jsondata_message', namespace='/generate_data')
def handle_client_message2(message_data):
    message = message_data['message']
    process_data2(message)
    
@app.route('/init',methods=['GET','POST'])
def init():
    data=request.get_json()
    video_name=data.get('videoname')
    video_data=get_video_data(video_name)
    return_data={
        'nodejson':video_data['nodejson'],
        'edgejson':video_data['edgejson'],
        'treejson':video_data['treejson'],
        'content':video_data['content'],
        'summary':video_data['summary']
        }
    return return_data 

@app.route('/liancha',methods=['GET','POST'])
def liancha():
    data=request.get_json()
    node_name=data.get('node')
    video_ids=get_video_ids_by_node(node_name)
    print(video_ids)
    video_data=get_videos_data_by_ids(video_ids)
    video_data={'video_data':video_data}
    
    return video_data

@app.route('/upload', methods=['POST'])
def upload_file():
    if 'video' not in request.files:
        return jsonify({'error': 'No file part'})
    
    video = request.files['video']
    
    video_name = request.form.get('videoName')
    
    video_tag = request.form.get('videoTag')
    
    # Save the file to a location
    video_path = 'temp/temp_video.mp4'
    
    audio_path = 'temp/temp_audio.mp3'

    video.save(video_path)
    
    
    # 调用处理视频的函数来提取音频
    subprocess.run(["python", "transformer.py", "--param1", video_path, "--param2", audio_path, "--param3", video_name, "--param4", video_tag])

    
    
    return jsonify({'message': 'File uploaded successfully'})




# 启动 Flask 应用程序
if __name__ == '__main__':
    # app.run(debug=True,port=8090)
    socketio.run(app, debug=True, port=8090)
